package com.flca.frw.zk.comp;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zul.Window;
import org.zkoss.zul.api.Textbox;

import com.flca.frw.log.StacktraceHelper;
import com.flca.frw.zk.util.Alert;

public class ErrorMessagesCtrl extends Window {

	private static final long serialVersionUID = -7090123268480300724L;

	private Exception exception;
	
	private Component container;
	
	public static void show(Exception anException) 
	{
		ErrorMessagesCtrl errmsg = getErrorMessageCtrl();
		errmsg.setTop("100px");
		errmsg.setup(anException);
		try {
			errmsg.doOverlapped();
		} catch (Exception e1) {
		} 
	}
	
	public static void show(Component aContainer, Exception anException) 
	{
		ErrorMessagesCtrl ctrl = (ErrorMessagesCtrl) aContainer.getFirstChild();
		ctrl.setMessage(aContainer, anException.getMessage());
	}

	private void setup(Exception anException)
	{
		exception = anException;
		Textbox textbox = (Textbox) getFellow("idErrorMsg");
		textbox.setValue(anException.getMessage());
	}

	private void setMessage(Component aContainer, String aMsg)
	{
		container = aContainer;
		container.setVisible(true);
		Textbox textbox = (Textbox) getFellow("idErrorMsg");
		textbox.setValue(aMsg);
	}
	
	public void onClose()
	{
		if (container != null) {
			container.setVisible(false);
		} else {
			this.detach();
		}
		removeErrMsgWindow();
	}

	public void onShowStacktrace() 
	{
		String stacktrace = StacktraceHelper.getStacktrace(exception);
		Alert.show(stacktrace);
	}
	
	private static ErrorMessagesCtrl getErrorMessageCtrl() 
	{
		ErrorMessagesCtrl result = null;
		
		result = (ErrorMessagesCtrl) Executions.getCurrent().getDesktop().getSession().
			getAttribute(ErrorMessagesCtrl.class.getSimpleName());
		if (result == null) {
			result = (ErrorMessagesCtrl) Executions.createComponents("/pages/comp/ErrorMessages.zul", null, null);
			saveErrMsgWindow(result);
		}
		return result;
	}
	
	private static void saveErrMsgWindow(ErrorMessagesCtrl aCtrl)
	{
		Executions.getCurrent().getDesktop().getSession().
			setAttribute(ErrorMessagesCtrl.class.getSimpleName(), aCtrl);
	}
	
	private static void removeErrMsgWindow()
	{
		Executions.getCurrent().getDesktop().getSession().
			removeAttribute(ErrorMessagesCtrl.class.getSimpleName());
	}
}
